// pages/orgIntroEdit/orgIntroEdit.js
const app = getApp();
const qiniu = require("../../utils/qiniu.min.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    description: "",
    isbtn: true,
    isText:true,
    imgTextList:[{
      contentType:0,
      content:"",
      contentSize:"",
    }],
    lock:false,
    videoshow:true,
  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },
  //文本
  imgTextInput(e) {
    var index = e.currentTarget.dataset.index;
    var temp_str = 'imgTextList[' + index + '].content';
    this.setData({
      [temp_str]: e.detail.value
    })
  },

  //增加文本
  addText() {
    this.data.imgTextList.push({
      contentType: 0,
      content: "",
    })
    this.setData({
      imgTextList: this.data.imgTextList
    })
  },
  // 增加图片
  addImg() {
    var that = this;
    app.getQiNiuToken(function (res) {
      var countnum = 3
      var qiniuconfig = res;
      wx.chooseImage({
        count: countnum,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          console.log('图片信息', res)
          var size = res.tempFiles[0].size / 1024;
          if (size % 1 === 0){
          }else{
            size = parseFloat((res.tempFiles[0].size / 1024).toFixed(1));
          }
          const filepathArray = res.tempFilePaths
          for (let i = 0; i < filepathArray.length; i++) {
            qiniu.upload(filepathArray[i], res => {
              that.data.imgTextList.push({
                contentType: 1,
                content: res.imageURL,
                contentSize:size
              })
              that.setData({
                imgTextList: that.data.imgTextList
              })
            }, (error) => {
              // console.log('error' + error)
            }, {
                uploadURL: 'https://upload.qiniup.com',
                region: 'ECN',
                domain: qiniuconfig.qiniuDomain,
                uptoken: qiniuconfig.upToken,
              })
          }

        }
      })
    });
    
  },
  // 视频全屏
  isbtn(e){
    console.log('视频全屏',e)
    if (e.detail.fullScreen){
      this.toggle('isbtn',false)
    }else{
      this.toggle('isbtn', true)
    }
  },
  //增加视频
  addvideo() {
    var that = this;
    app.getQiNiuToken(function(res) {
      var countnum = 3
      var qiniuconfig = res;
      wx.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 15,
        camera: 'back',
        success(res) {
          console.log('视频内容', res)
          const contentSize = that.except(res.size, 1024).toFixed(2)
          console.log('视频内容大小', contentSize)
          const videoTime = Math.round(res.duration)
          const filepathArray = res.tempFilePath
          qiniu.upload(filepathArray, res => {
            that.data.imgTextList.push({
              contentType: 2,
              content: res.imageURL,
              contentSize: contentSize,
              videoTime: videoTime,
            })
            that.setData({
              imgTextList: that.data.imgTextList
            })
          }, (error) => {
            // console.log('error' + error)
          }, {
            uploadURL: 'https://upload.qiniup.com',
            region: 'ECN',
            domain: qiniuconfig.qiniuDomain,
            uptoken: qiniuconfig.upToken,
          })

        }
      })
    });
  },
  except(arg1, arg2) {
    var t1 = 0,
      t2 = 0,
      r1, r2;
    try {
      t1 = arg1.toString().split(".")[1].length
    }
    catch (e) {

    }
    try {
      t2 = arg2.toString().split(".")[1].length
    }
    catch (e) {

    }
    r1 = Number(arg1.toString().replace(".", ""));
    r2 = Number(arg2.toString().replace(".", ""));
    return (r1 / r2) * Math.pow(10, t2 - t1);
  },
  //移除
  removeGroup(e) {
    var that = this;
    if (e.currentTarget.dataset.item.content){
      wx.showModal({
        title: '',
        content: '是否确认删除？',
        success(res) {
          if (res.confirm) {
            that.removeArray(that.data.imgTextList, e.currentTarget.dataset.item);
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }else{
      that.removeArray(that.data.imgTextList, e.currentTarget.dataset.item);
    }
  },
  //移除数组
  removeArray(_arr, _obj) {
    var length = _arr.length;
    for (var i = 0; i < length; i++) {
      if (_arr[i].content == _obj.content) {
        if (i == 0) {
          _arr.shift(); //删除并返回数组的第一个元素
          return this.setData({
            imgTextList: _arr
          });
        }
        else if (i == length - 1) {
          _arr.pop();  //删除并返回数组的最后一个元素
          return this.setData({
            imgTextList: _arr
          });
        }
        else {
          _arr.splice(i, 1); //删除下标为i的元素
          return this.setData({
            imgTextList: _arr
          });
        }
      }
    }
  },
  // 交换数组
  swapArray(arr, index1, index2) {
    // var temp = arr[index1]
    // arr.splice(index1, 1)
    // arr.splice(index2, 0, temp)
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
  },
  // 移动
  zIndexUp(e){
    this.toggle("videoshow", false);
    var data = e.currentTarget.dataset;
    var index = data.index;
    var type = data.type;
    if ((index + 1 != this.data.imgTextList.length && type == 1) || (index != 0 && type == 2 ) ){
      this.swapArray(this.data.imgTextList, index, type==1 ? index + 1 : index - 1);
      this.toggle("imgTextList", this.data.imgTextList);
      this.toggle("videoshow", true);
    }
    console.log('交换后数组', this.data.imgTextList)
  },
  
  onSave: function() {
    var that = this;
    if (that.data.lock) {
      return
    }
    that.toggle('lock', true);
    var timeoutflag = null;
    if (timeoutflag != null) {
      clearTimeout(timeoutflag);
    }
    timeoutflag = setTimeout(function () {
      that.toggle('lock', false);
    }, 3000);
    var data = that.data;
    var html = "";
    for (var item of this.data.imgTextList){
      // if (!item.content){
      //   wx.showToast({
      //     title: '内容不能为空',
      //     icon: 'none',
      //   });
      //   return
      // }
      if (item.contentType == 0 ){
        item.content = item.content.trim().replace(new RegExp(" ", "gm"), "&nbsp;");
        let reg = new RegExp('\n', 'g')
        item.content = item.content.replace(reg, "<br>");
        html += '<p>' + item.content + '</p >';
      } else if (item.contentType == 1){
        // html += '<img src=' + item.content + ' />'
        html += `<img src=${item.content}?imageView2/1/q/30/format/jpg/ignore-error/1 style='margin-top:5px'/>`
      } else if (item.contentType == 2){
        html += '<video style="margin-top:5px" width="100%" webkit-playsinline = "true" playsinline = "true" controls controlslist = "nodownload" poster ="' + item.content + '?vframe/jpg/offset/0/imageslim/imageView2/1/interlace/1/ignore-error/1"><source type="video/mp4" src="' + item.content + '"></video >'
      }
      console.log(html)
    }
    if (!this.data.id) {
      wx.showToast({
        title: '保存成功',
        icon: 'none'
      });
      var contents = this.data.imgTextList;
      setTimeout(()=>{
        let pages = getCurrentPages();  // 当前页的数据，可以输出来看看有什么东西
        let prevPage = pages[pages.length - 2];  // 上一页的数据，也可以输出来看看有什么东西
        prevPage.setData({
          ["detail.contents"]: contents,
          ["detail.orgIntroduce"]: html
        })
        wx.navigateBack({})
        // wx.navigateBack({
        //   url: '/pages/creat/creat?contents=' + contents + '&orgIntroduce=' + html,
        // })
      },500)
      return
    }
    var param = {
      relationId: data.id,
      type:1,
      contents: this.data.imgTextList,
      orgIntroduce: html
    };
    app.req({
      url: "orgmini/contentEdit/edit",
      data: param,
      success: function(res) {
        if (200 == res.code) {
          wx.navigateBack();
          wx.showToast({
            title: '保存成功',
            icon: 'none'
          });
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.id){
      this.toggle("id", options.id);
      this.detail();
    }
    if (options.contents){
      this.toggle("imgTextList", JSON.parse(options.contents));
    }
  },
  detail: function() {
    var that = this;
    app.req({
      url: "orgmini/org/newGetOrgDetailedInfo",
      data: {
        orgId: that.data.id
      },
      success: function(res) {
        if (200 == res.code) {
          if (res.data.contents.length != 0){
            for (var item of res.data.contents){
              if (!item.contentType){
                item.content = item.content.trim().replace(/<br>/g, "\n").replace(/&nbsp;/g, " ")
              }
            }
            that.toggle("imgTextList", res.data.contents);
          }
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    // app.getUserInfo(function(userInfo) {
    //   that.detail();
    // });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    console.log("下拉")
    return true;
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})